package com.bw.z.mvp.view.news;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bw.z.App;
import com.bw.z.R;
import com.bw.z.db.UserTable;
import com.bw.z.mvp.HttpCode;
import com.bw.z.mvp.base.view.BaseFragment;
import com.bw.z.mvp.contract.NewsContract;
import com.bw.z.mvp.di.DaggerNewsComponent;
import com.bw.z.mvp.di.NewsModules;
import com.bw.z.mvp.model.entity.BaseEntity;
import com.bw.z.mvp.model.entity.ChannelEntity;
import com.bw.z.mvp.model.entity.TextBannerEntity;
import com.bw.z.mvp.presenter.NewsPresenter;
import com.bw.z.mvp.view.news.adapter.NewsVpAdapter;
import com.bw.z.mvp.view.news.adapter.TextBannerAdapter;
import com.bw.z.utils.SpUtils;
import com.flyco.tablayout.SlidingTabLayout;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.transformer.ZoomOutPageTransformer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NewsFragment extends BaseFragment<NewsPresenter>
        implements NewsContract.NewView, OnBannerListener<TextBannerEntity.Values>, View.OnClickListener {

    private Banner<TextBannerEntity.Values, TextBannerAdapter> newsTextBanner;
    private SlidingTabLayout newsTab;
    private ViewPager newsVp;
    private List<Fragment> fragments;
    private NewsVpAdapter newsVpAdapter;
    private TextBannerAdapter textBannerAdapter;
    private ImageView newsMoreImg;

    @Override
    public int bindLayout() {
        return R.layout.fragment_news;
    }

    @Override
    public void initView() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("newsTab");
        getContext().registerReceiver(new MyBroadcast(), intentFilter);

        newsTextBanner = f(R.id.news_text_banner);
        newsTab = f(R.id.news_tab);
        newsVp = f(R.id.news_vp);
        newsMoreImg = f(R.id.news_more_img);
        newsMoreImg.setOnClickListener(this::onClick);
    }

    @Override
    public void inject() {
        DaggerNewsComponent.builder().newsModules(new NewsModules(this)).build().injectNews(this);
    }

    @Override
    public void initData() {
        fragments = new ArrayList<>();
        //获取顶部文字banner数据源
        List<UserTable> users = App.getInstance().getDaoSession().queryBuilder(UserTable.class).list();
        boolean flag = users.size() == 0;

        //获取频道数据源
        Map<String, Object> bannerMap = new HashMap<>();
        bannerMap.put("code", HttpCode.TEXTBANNERCODE);

        Map<String, Object> channelMap = new HashMap<>();
        channelMap.put("code", HttpCode.USERCHANNELCODE);
        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        // PhoneUtils.getIMEI()
        // System.currentTimeMillis()
        Long id = SpUtils.readDataLong("user_id");
        int user_id = 1;
        if (id != 0l)
            user_id = App.dbManager.getDaoSession().getUserTableDao().load(SpUtils.readDataLong("user_id")).getUser_id();
        channelMap.put("imie", flag ? System.currentTimeMillis() : "");
        channelMap.put("userId", user_id);
        p.requestAll(bannerMap, channelMap);
    }

    class MyBroadcast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("newsTab")) {
                List<UserTable> users = App.getInstance().getDaoSession().queryBuilder(UserTable.class).list();
                boolean flag = users.size() == 0;
                Map<String, Object> channelMap = new HashMap<>();
                channelMap.put("code", HttpCode.USERCHANNELCODE);
                if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
                // PhoneUtils.getIMEI()
                // System.currentTimeMillis()
                Long id = SpUtils.readDataLong("user_id");
                int user_id = 1;
                if (id != 0l)
                    user_id = App.dbManager.getDaoSession().getUserTableDao().load(SpUtils.readDataLong("user_id")).getUser_id();
                channelMap.put("imie", flag ? System.currentTimeMillis() : "");
                channelMap.put("userId", user_id);
                p.requestAll(channelMap);
            }
        }
    }

    @Override
    public void refreshAll(BaseEntity baseEntity) {
        if (baseEntity instanceof TextBannerEntity) {
            //文字banner返回
            TextBannerEntity textBannerEntity = (TextBannerEntity) baseEntity;
            LogUtils.e("TextBannerEntity:" + textBannerEntity.values);
            if (textBannerEntity.getValues() == null) {
                ToastUtils.showShort("文字广告数据丢失");
                return;
            }
            textBannerAdapter = new TextBannerAdapter(textBannerEntity.getValues());
            newsTextBanner.setAdapter(textBannerAdapter)
                    .setOrientation(Banner.VERTICAL)
                    .setPageTransformer(new ZoomOutPageTransformer())
                    .setOnBannerListener(this);
        } else if (baseEntity instanceof ChannelEntity) {
            //频道列表数据
            //按照频道数量以及频道id初始化fragments
            ChannelEntity channelEntity = (ChannelEntity) baseEntity;
            if (channelEntity.getValues() == null) {
                ToastUtils.showShort("无频道数据");
                return;
            }
            for (int i = 0; i < channelEntity.getValues().size(); i++) {
                fragments.add(new ContentNewsFragment(channelEntity.getValues().get(i).channel_id));
            }
            newsVpAdapter = new NewsVpAdapter(getFragmentManager(), fragments, channelEntity.getValues());
            newsVp.setAdapter(newsVpAdapter);
            newsTab.setViewPager(newsVp);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        newsTextBanner.start();
    }

    @Override
    public void onStop() {
        super.onStop();
        newsTextBanner.stop();
    }

    @Override
    public void refreshRecyclerView(BaseEntity baseEntity) {

    }

    @Override
    public void loadMoreRecyclerView(BaseEntity baseEntity) {

    }

    @Override
    public void OnBannerClick(TextBannerEntity.Values data, int position) {
        // 点击跳转
        Toast.makeText(getContext(), "点击广告:" + data.news_title, Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onClick(View v) {
        startPage(ChannelActivity.class);
    }
}